"use client"

import { useState, useEffect, useMemo } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Textarea } from "@/components/ui/textarea"
import { Copy, MessageCircle, Mail, Share2 } from "lucide-react"
import type { CartItem } from "@/types"

interface ShareModalProps {
  isOpen: boolean
  onClose: () => void
  orderData: {
    items: CartItem[]
    total: number
    itemCount: number
    timestamp: string
  }
  deliveryMethod: "pickup" | "delivery"
  deliveryFee: number
  finalTotal: number
}

export function ShareModal({ isOpen, onClose, orderData, deliveryMethod, deliveryFee, finalTotal }: ShareModalProps) {
  const [isCopying, setIsCopying] = useState(false)
  const [isWxSdkReady, setIsWxSdkReady] = useState(false)

  // ✅ 内联环境检测函数 - 直接写在组件内部
  const getEnvironmentInfo = () => {
    // 首先检查是否在浏览器环境中 [9,10](@ref)
    if (typeof window === 'undefined' || !window.document) {
      return { isMobile: false, isWechat: false, supportsShare: false, supportsClipboard: false }
    }

    const userAgent = navigator.userAgent
    return {
      isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent),
      isWechat: /MicroMessenger/i.test(userAgent),
      supportsShare: !!navigator.share,
      supportsClipboard: !!(navigator.clipboard && navigator.clipboard.writeText),
      userAgent
    }
  }

  // ✅ 使用 useMemo 缓存环境信息，避免重复计算 [11](@ref)
  const envInfo = useMemo(() => getEnvironmentInfo(), [])

  const orderText = `🍜 宿舍泡面订单

📋 订单详情：
${orderData.items.map((item) => `• ${item.name} × ${item.quantity} = ¥${(item.price * item.quantity).toFixed(2)}`).join("\n")}

💰 费用明细：
商品小计：¥${orderData.total.toFixed(2)}
配送费：${deliveryFee > 0 ? `¥${deliveryFee.toFixed(2)}` : "免费"}
总计：¥${finalTotal.toFixed(2)}

🚚 配送方式：${deliveryMethod === "delivery" ? "送货上门" : "到店自取"}

⏰ 下单时间：${new Date(orderData.timestamp).toLocaleString("zh-CN")}

请确认订单并安排制作，谢谢！`

  // ✅ 微信JS-SDK初始化 [1,2](@ref)
  // 在useEffect中修改微信SDK初始化部分
useEffect(() => {
  const initWechatSDK = async () => {
    const env = getEnvironmentInfo()
    if (!isOpen || !env.isWechat) return

    try {
      const currentUrl = window.location.href.split('#')[0]
      const configData = await fetchWechatConfig(currentUrl)
      
      // 检查wx对象是否存在
      if (window.wx) {
        const wxInstance = window.wx; // 缓存到局部变量
        
        wxInstance.config({
          debug: false,
          appId: configData.appId,
          timestamp: configData.timestamp,
          nonceStr: configData.nonceStr,
          signature: configData.signature,
          jsApiList: [
            'updateAppMessageShareData',
            'updateTimelineShareData'
          ]
        })

        wxInstance.ready(() => {
          console.log("微信JS-SDK 初始化成功")
          setIsWxSdkReady(true)
          
          // 使用缓存的wxInstance，TypeScript知道它一定存在
          wxInstance.updateAppMessageShareData({
            title: '宿舍泡面订单',
            desc: orderText.substring(0, 50) + '...',
            link: window.location.href,
            imgUrl: 'https://your-domain.com/logo.png',
            success: () => console.log('分享朋友设置成功')
          })

          wxInstance.updateTimelineShareData({
            title: '宿舍泡面订单',
            link: window.location.href,
            imgUrl: 'https://your-domain.com/logo.png',
            success: () => console.log('分享朋友圈设置成功')
          })
        })

        wxInstance.error((res) => {
          console.error("微信JS-SDK 初始化失败", res)
          setIsWxSdkReady(false)
        })
      }
    } catch (error) {
      console.error("微信SDK初始化失败:", error)
    }
  }

  if (isOpen) {
    initWechatSDK()
  }
}, [isOpen, orderText])

  // ✅ 复制功能（兼容移动端） [9](@ref)
  const handleCopy = async () => {
    setIsCopying(true)
    try {
      if (envInfo.supportsClipboard) {
        await navigator.clipboard.writeText(orderText)
      } else {
        // 降级方案
        const textArea = document.createElement('textarea')
        textArea.value = orderText
        textArea.style.position = 'fixed'
        textArea.style.opacity = '0'
        document.body.appendChild(textArea)
        textArea.select()
        
        const successful = document.execCommand('copy')
        document.body.removeChild(textArea)
        
        if (!successful) {
          throw new Error('复制失败')
        }
      }
      
      // 显示成功提示
      setTimeout(() => setIsCopying(false), 2000)
    } catch (error) {
      console.error("复制失败:", error)
      // 终极降级方案：提示用户手动复制
      alert('请手动选择文本并按Ctrl+C（或长按选择复制）')
      setIsCopying(false)
    }
  }

  // ✅ 系统分享（智能降级） [9](@ref)
  const handleNativeShare = async () => {
    try {
      if (envInfo.supportsShare && envInfo.isMobile) {
        await navigator.share({
          title: "宿舍泡面订单",
          text: orderText,
        })
      } else {
        // 不支持系统分享时降级到复制
        await handleCopy()
        if (envInfo.isMobile) {
          alert('订单信息已复制，请粘贴到社交应用分享')
        }
      }
    } catch (error) {
      console.error("分享失败:", error)
      // 分享失败后也降级到复制
      await handleCopy()
    }
  }

  // ✅ 微信分享（优化版） [1,2](@ref)
  const handleWechatShare = async () => {
    if (envInfo.isWechat) {
      if (isWxSdkReady) {
        // 在微信环境中，SDK就绪后点击分享按钮会直接调起微信分享界面
        console.log('微信分享已准备就绪，将调起分享界面')
        // 这里不需要额外操作，SDK会自动处理分享调起
      } else {
        // SDK未就绪，降级处理
        await handleCopy()
        alert('微信分享功能正在准备中，订单信息已复制，请粘贴到微信发送给商家')
      }
    } else {
      // 非微信环境
      await handleCopy()
      alert('订单信息已复制，请粘贴到微信发送给商家')
    }
  }

  // ✅ 邮件分享（优化兼容性）
  const handleEmailShare = () => {
    const subject = encodeURIComponent("宿舍泡面订单")
    const body = encodeURIComponent(orderText)
    const mailtoLink = `mailto:?subject=${subject}&body=${body}`
    
    // 根据设备类型采用不同策略
    if (envInfo.isMobile) {
      window.location.href = mailtoLink
    } else {
      window.open(mailtoLink, '_blank')
    }
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Share2 className="h-5 w-5" />
            转发订单
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-4">
          {/* 订单预览 */}
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm">订单预览</CardTitle>
            </CardHeader>
            <CardContent>
              <Textarea 
                value={orderText} 
                readOnly 
                className="min-h-[200px] text-xs font-mono resize-none" 
              />
            </CardContent>
          </Card>

          {/* 分享选项 - 根据环境智能显示 */}
          <div className="grid grid-cols-2 gap-3">
            <Button
              variant="outline"
              className="flex flex-col gap-2 h-auto py-4 bg-transparent"
              onClick={handleCopy}
              disabled={isCopying}
            >
              <Copy className="h-5 w-5" />
              <span className="text-xs">{isCopying ? "已复制" : "复制文本"}</span>
            </Button>

            <Button
              variant="outline"
              className="flex flex-col gap-2 h-auto py-4 bg-transparent"
              onClick={handleWechatShare}
            >
              <MessageCircle className="h-5 w-5" />
              <span className="text-xs">微信分享</span>
            </Button>

            <Button
              variant="outline"
              className="flex flex-col gap-2 h-auto py-4 bg-transparent"
              onClick={handleEmailShare}
            >
              <Mail className="h-5 w-5" />
              <span className="text-xs">邮件发送</span>
            </Button>

            {/* 在微信环境中隐藏系统分享按钮 */}
            {!envInfo.isWechat && (
              <Button
                variant="outline"
                className="flex flex-col gap-2 h-auto py-4 bg-transparent"
                onClick={handleNativeShare}
              >
                <Share2 className="h-5 w-5" />
                <span className="text-xs">系统分享</span>
              </Button>
            )}
          </div>

          <div className="flex gap-2">
            <Button variant="outline" onClick={onClose} className="flex-1 bg-transparent">
              取消
            </Button>
            <Button onClick={handleCopy} className="flex-1">
              {isCopying ? "已复制" : "复制并关闭"}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}

// ✅ 后端API调用函数（需要您根据实际后端接口实现）
async function fetchWechatConfig(url: string) {
  try {
    // 这里需要您替换为实际的后端API端点
    const response = await fetch('/api/wechat-config', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ url })
    })
    
    if (!response.ok) {
      throw new Error('获取微信配置失败')
    }
    
    return await response.json()
  } catch (error) {
    console.error('获取微信配置失败:', error)
    throw error
  }
}